package com.bjsdzk.common.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 胜顶智控平台管理
 * Map工具类
 *
 * @author YangTang
 * @time 2019/6/28.
 */
public class MapUtils {
    public static <T> Map<String, List<T>> listToMap(Class<Map> type, List<T> list, String fieldName) throws IllegalAccessException, InstantiationException {
        try {
            Map<String, List<T>> map = type.newInstance();
            for (T t : list) {
                Class<?> aClass = t.getClass();
                Field field = aClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                String o = (String) field.get(t);
                if (map.containsKey(o)) {
                    map.get(o).add(t);
                } else {
                    List<T> tmpList = new ArrayList<>();
                    tmpList.add(t);
                    map.put(o, tmpList);
                }
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
